<template>
  <view
    v-if="componentStatus.status == 'selected'"
    :style="{
      position: fixed ? 'sticky' : 'relative',
      top: fixed ? `${props.topStickyHeight + 5}px` : 'auto',
      // TODO =1 会被部分视频覆盖，>1 会覆盖留言等弹窗，待优化
      zIndex: 1,
    }"
  >
    <view :class="{ 'service-list': true, selected: componentStatus.status === 'selected' }">
      <template v-if="componentStatus.status === 'selected'">
        <view class="service-header selected">
          <text class="service-title selected">正在为您服务</text>
        </view>
        <view class="service-item selected" style="margin: auto; width: fit-content; height: fit-content">
          <view class="service-icon">
            <view class="chatIcon icon-kefu" style="font-size: 50rpx"></view>
          </view>
          <text class="service-name selected">{{ componentStatus.selectedService?.servicePersonName }}</text>
          <view class="chatIcon icon-guaduan btn-end" @tap="handleEndClick"></view>
        </view>
      </template>

      <template v-else-if="componentStatus.status === 'connecting'">
        <view class="service-header">
          <text class="service-title">正在连接中...</text>
        </view>
      </template>

      <template v-else>
        <view class="service-header">
          <view class="service-title" style="flex: auto">您可以选择座席</view>
          <view style="text-align: right">
            <view
              class="chatIcon icon-jiazai_shuaxin"
              :class="{
                loading: componentStatus.refreshStatus === 'loading',
              }"
              @tap="handleRefreshClick"
              style="width: fit-content; font-size: 50rpx"
            >
            </view>
          </view>
        </view>

        <scroll-view scroll-y class="service-scroll">
          <view v-if="props.list.length === 0 && componentStatus.refreshStatus !== 'loading'" class="service-empty">
            <text class="chatIcon icon-bangzhu" style="font-size: 80rpx; color: var(--theme-color, #ffc549)"></text>
            <text>{{ componentStatus.emptyText }}</text>
          </view>
          <view class="service-grid">
            <view v-for="(item, index) in props.list" :key="index" class="service-item" @tap="handleServiceClick(item)">
              <view class="service-icon">
                <view class="chatIcon icon-kefu"></view>
                <view class="service-status" :class="{ online: item.onlineStatus }"></view>
              </view>
              <text class="service-name">{{ item.servicePersonName }}</text>
            </view>
          </view>
        </scroll-view>
      </template>
    </view>
  </view>
</template>

<script setup lang="ts">
import { defineEmits, onMounted, onUnmounted, reactive } from "vue";
import { removeConversation } from "../api";

const props = defineProps({
  list: {
    type: Array,
    default: () => [],
  },
  fixed: {
    type: Boolean,
    default: false,
  },
  // 顶部 sticky 高度 （px）
  topStickyHeight: {
    type: Number,
    default: 10,
  },
});

const componentStatus = reactive({
  status: "init",
  // 当前选中的客服
  selectedService: null,
  // 刷新状态
  refreshStatus: "init",
  // 无客服提示
  emptyText: "暂无客服在线,您可以拨打客服热线或留言\n我们将在收到留言后尽快回复您",
});

const emits = defineEmits(["select", "refresh", "end-call"]);

// 选择客服
const handleServiceClick = (service: any) => {
  emits("select", service);
};

// 刷新客服列表
const handleRefreshClick = () => {
  componentStatus.refreshStatus = "loading";

  setTimeout(() => {
    // 刷新客服列表
    emits("refresh");
    componentStatus.refreshStatus = "init";
  }, 800);
};

// 结束会话
const handleEndClick = async () => {
  emits("end-call", componentStatus.selectedService);
  try {
    const params = {
      channelId: componentStatus.selectedService?.channel,
    };
    const { success } = await removeConversation(params);
    if (!success) throw new Error("结束失败");
  } catch (error) {
    console.error(error);
    uni.showToast({
      title: "结束失败",
      icon: "none",
    });
  }
};

onMounted(() => {
  // 监听 客服列表更新状态
  uni.$on("KN-IM:serviceListStatusChange", (event: any) => {
    console.log("KN-IM:serviceListStatusChange -> event", event);
    const { data, type } = event;
    componentStatus.status = type;
    if (type === "selected") {
      componentStatus.selectedService = data;
    }
  });
});

onUnmounted(() => {
  uni.$off("KN-IM:serviceListStatusChange");
});
</script>

<style scoped lang="scss">
$default-color: #4ba0fd;
$default-bg-color: #e7f3ff;

.service-list {
  background-color: $default-bg-color;
  border-radius: 12rpx;
  color: #333;
  margin: 20rpx 0;
  padding: 20rpx;
  border: 2px solid $default-color;
  transition: all 0.5s;

  &.selected {
    display: flex;
    padding: 0 10rpx;
    // border: 2px solid #4bf5fd;
    // background-color: #d5f7ff;

    .service-title {
      font-size: 25rpx;
    }

    .service-item {
      padding: 0 15rpx;
      flex: auto;
      display: flex;
      width: fit-content;
    }

    .service-name {
      flex: auto;
      color: $default-color;
    }

    .btn-end {
      color: #ff7171;
      font-size: 32rpx;
    }
  }
}

.service-header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #f5f5f5;

  .service-title {
    font-size: 32rpx;
    font-weight: bold;
  }
}

.service-scroll {
  max-height: 400rpx;

  .service-empty {
    font-size: 28rpx;
    color: #999;
    text-align: center;
    padding: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
}

.service-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  padding: 20rpx;
}

.service-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 10rpx;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;

  &:active {
    transform: scale(0.95);
  }

  .service-icon {
    position: relative;
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;

    .chatIcon {
      font-size: 60rpx;
      color: $default-color;
    }

    .service-status {
      position: absolute;
      right: 0;
      bottom: 0;
      width: 20rpx;
      height: 20rpx;
      border-radius: 50%;
      background-color: #999;
      border: 4rpx solid #fff;

      &.online {
        background-color: #52c41a;
      }
    }
  }

  .service-name {
    font-size: 28rpx;
    color: #333;
    font-weight: bold;
  }
}

.loading {
  // 点击之后执行 2s 动画，并且收起点击不立即删除动画
  animation: rotate 1s linear infinite;
}

// 旋转动画
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
